import router, { developRoute } from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false })
const whiteList = ['/login', '/auth-redirect']

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  // 白名单放行
  if (whiteList.indexOf(to.path) !== -1) {
    next()
    NProgress.done()
    return
  }

  const hasToken = getToken()
  // 无token 跳转登录                                                                                                                                                                                                                                                                        登录页面
  if (!hasToken) {
    next(`/login?redirect=${to.path}`)
    NProgress.done()
    return
  }

  const hasRoles = store.getters.roles && store.getters.roles.length > 0

  // 已加载角色权限放行
  if (hasRoles) {
    next()
    NProgress.done()
    return
  }

  // 加载角色菜单权限
  try {
    // 刷新用户信息、并返回用户角色路由表
    let funclist = await store.dispatch('user/getInfo')
    // console.log('####addRouteOfRule 0', funclist)

    // 加载角色路由
    const accessRoutes = await store.dispatch('permission/addRouteOfRule', funclist)

    next({ ...to, replace: true })
  } catch (error) {
    // console.log('permission error:', error)
    await store.dispatch('user/resetToken')
    Message.error(error || 'Has Error')
    next(`/login?redirect=${to.path}`)
    NProgress.done()
  }
})

router.afterEach(() => {
  NProgress.done()
})
